package com.freewater.javabase.demo.network.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NistimeGetter {
    public static void main(String[] args) {
        try (Socket socket = new Socket("ntp1.glb.nist.gov", 13)) {
            // 设置会阻塞的Socket操作的超时时间，例如以下这些方法：
            // ServerSocket.accept();
            // SocketInputStream.read();
            // DatagramSocket.receive();
            socket.setSoTimeout(15 * 1000);
            final StringBuilder time = new StringBuilder();
            try (final InputStream inputStream = socket.getInputStream();
                 // nist 协议规定的，必须使用ASCII字符编码
                 final InputStreamReader reader = new InputStreamReader(inputStream, "ASCII")) {
                for (int c = reader.read(); c != -1; c = reader.read()) {
                    time.append((char) c);
                }
                final String originalDataTime = time.toString();
                System.out.println(">>>>> original: " + originalDataTime.trim());
                final Date dateTime = parseTime(originalDataTime);
                final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(">>>>> time: " + sdf.format(dateTime));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Date parseTime(String s) throws ParseException {
        final String[] parts = s.split(" ");
        final String time = parts[1] + " " + parts[2] + " UTC";
        final SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss z");
        final Date dateTime = sdf.parse(time);
        return dateTime;
    }
}
